<template>
  <el-row>
    <el-row :gutter="10">
      <el-col :span="8" style="text-align: left">
        <span class="demonstration">选择月份范围</span>
        <el-date-picker
            v-model="date_range"
            type="monthrange"
            align="center"
            size="large"
            @change="selectChange"
            range-separator="至"
            start-placeholder="开始月份"
            end-placeholder="结束月份"
            value-format="yyyy-MM"
            :picker-options="pickerOptions">
        </el-date-picker>
      </el-col>
      <el-col :span="16">
        <span class="demonstration">设备型号</span>
        <el-select
            v-model="select_models"
            multiple
            filterable
            collapse-tags
            @change="selectChange"
            style="width: 150px;"
            placeholder="设备型号">
          <el-option
              v-for="item in product_models"
              :key="item.value"
              :label="item.label"
              :value="item.value">
          </el-option>
        </el-select>
        &
        <el-select
            v-model="select_sub_models"
            multiple
            filterable
            collapse-tags
            @change="selectChange"
            style="width: 150px;"
            placeholder="次级设备型号">
          <el-option
              v-for="item in sub_product_models"
              :key="item.value"
              :label="item.label"
              :value="item.value">
          </el-option>
        </el-select>
        <el-select
            v-model="select_feedback_type"
            multiple
            filterable
            collapse-tags
            @change="selectChange"
            style="margin-left: 20px; width: 150px;"
            placeholder="反馈单类型">
          <el-option
              v-for="item in feedback_types"
              :key="item.value"
              :label="item.label"
              :value="item.value">
          </el-option>
        </el-select>
      </el-col>
    </el-row>
    <el-row style="text-align: left">
      <el-col :span="6">
        <span class="demonstration">客户医院</span>
        <el-select
            v-model="select_hospitals"
            multiple
            filterable
            collapse-tags
            @change="selectSubChange"
            placeholder="选择医院">
          <el-option
              v-for="item in hospitals"
              :key="item.value"
              :label="item.label"
              :value="item.value">
          </el-option>
        </el-select>
      </el-col>
      <el-col :span="18">
        <el-tag
            v-for="tag in select_hospitals"
            :key="tag"
            closable
            type="success"
            @close="handleHospitalTagClose(tag)">
          {{ tag }}
        </el-tag>
      </el-col>
    </el-row>
<!--    <el-row style="text-align: left">-->
<!--      <el-col :span="6">-->
<!--        <span class="demonstration">临床科室</span>-->
<!--        <el-select-->
<!--            v-model="select_departments"-->
<!--            multiple-->
<!--            filterable-->
<!--            collapse-tags-->
<!--            @change="selectChange"-->
<!--            style="margin-right: 20px;"-->
<!--            placeholder="选择科室">-->
<!--          <el-option-->
<!--              v-for="item in departments"-->
<!--              :key="item.value"-->
<!--              :label="item.label"-->
<!--              :value="item.value">-->
<!--          </el-option>-->
<!--        </el-select>-->
<!--      </el-col>-->
<!--      <el-col :span="18">-->
<!--        <el-tag-->
<!--            v-for="tag in select_departments"-->
<!--            :key="tag"-->
<!--            closable-->
<!--            @close="handleDepartmentTagClose(tag)">-->
<!--          {{ tag }}-->
<!--        </el-tag>-->
<!--      </el-col>-->
<!--    </el-row>-->
    <el-divider></el-divider>
    <div id="feedback-figure-6"></div>
  </el-row>
</template>

<script>
import * as echarts from 'echarts';
import axios from 'axios'

axios.defaults.baseURL = '/api'
export default {
  data() {
    return {
      data: {},
      select_departments: [],
      departments: [],
      select_hospitals: [],
      hospitals: [],
      product_models: [],
      sub_product_models: [],
      select_models: ['SR2000'],
      select_sub_models: [],
      select_feedback_type: [],
      feedback_types: [],
      date_range: [],
      option: {
        tooltip: {
          trigger: 'axis',
          axisPointer: {
            type: 'cross',
            crossStyle: {
              color: '#999'
            }
          },
          formatter: function (params) {
            let result = "";
            for (let i = 0; i < params.length; i++) {
              if (params[i].data != 0) {
                result += params[i].marker + params[i].seriesName + '：' + params[i].data + '<br>'
              }
            }
            return params[0].name + '<br/>'
                + result

          }
        },
        toolbox: {
          feature: {
            dataView: {show: true, readOnly: false},
            magicType: {show: true, type: ['bar']},
            myTool: {
                show: true,
                title: 'export data',
                icon: 'path://path://M432.45,595.444c0,2.177-4.661,6.82-11.305,6.82c-6.475,0-11.306-4.567-11.306-6.82s4.852-6.812,11.306-6.812C427.841,588.632,432.452,593.191,432.45,595.444L432.45,595.444z M421.155,589.876c-3.009,0-5.448,2.495-5.448,5.572s2.439,5.572,5.448,5.572c3.01,0,5.449-2.495,5.449-5.572C426.604,592.371,424.165,589.876,421.155,589.876L421.155,589.876z M421.146,591.891c-1.916,0-3.47,1.589-3.47,3.549c0,1.959,1.554,3.548,3.47,3.548s3.469-1.589,3.469-3.548C424.614,593.479,423.062,591.891,421.146,591.891L421.146,591.891zM421.146,591.891', // 使用 SVG 路径作为图标
                onclick: function () {
                    this.exportChartData(this.select_hospitals)
                }.bind(this)
            },
            saveAsImage: {show: true}
          }
        },
        legend: {
          data: []
        },
        grid: {
          top: '5%',
          bottom: '20%'
        },
        xAxis: [
          {
            type: 'category',
            data: [],
            axisPointer: {
              type: 'shadow'
            },
            axisLabel: {
              interval: 0,
              rotate: 90
            }
          }
        ],
        yAxis: [
          {
            type: 'value',
            name: '数量',
            min: 0,
            max: 20,
            interval: 5,
            axisLabel: {
              formatter: '{value}'
            }
          }
        ],
        series: []
      },
      chart: null,
      pickerOptions: {
        shortcuts: [{
          text: '本月',
          onClick(picker) {
            picker.$emit('pick', [new Date(), new Date()]);
          }
        }, {
          text: '今年至今',
          onClick(picker) {
            const end = new Date();
            const start = new Date(new Date().getFullYear(), 0);
            picker.$emit('pick', [start, end]);
          }
        }, {
          text: '最近六个月',
          onClick(picker) {
            const end = new Date();
            const start = new Date();
            start.setMonth(start.getMonth() - 6);
            picker.$emit('pick', [start, end]);
          }
        }]
      },
    }
  },
  created() {
    this.initDatePicker();
    this.query_feedback_type();
    this.query_product_models();
    this.query_hospitals();
    this.query_departments();
    this.initPlot();
  },
  methods: {
    exportChartData(hospitals) {
      axios.post('/feedback/figure/6/data', {
            params: {
              date_list: this.date_range,
              product_models: this.select_models,
              sub_product_models: this.select_sub_models,
              feedback_type: this.select_feedback_type,
              hospitals: hospitals,
              departments: this.select_departments
            }
          }
      ).then(
          response => {
            let blob = new Blob([response.data], {type: 'text/csv; charset=utf-8'});
            const link = document.createElement('a');
            link.href = window.URL.createObjectURL(blob);
            link.download = `data_hospitals.csv`;
            if (hospitals.length === 1) {
              link.download = `data_${hospitals[0]}.csv`;
            }
            link.click();
            window.URL.revokeObjectURL(link.href);
          },
          // 失败
          error => {
            this.$message.error({message: error.response.data.message, showClose: true});
          })
    },
    handleHospitalTagClose(tag) {
      this.select_hospitals.splice(this.select_hospitals.indexOf(tag), 1);
      this.selectSubChange();
    },
    initDatePicker() {
      let end = new Date();
      let start = new Date();
      start.setMonth(start.getMonth() - 6);
      start = start.getFullYear() + '-' + (start.getMonth()+1);
      end = end.getFullYear() + '-' + (end.getMonth()+1);
      this.date_range = [start, end];
    },
    query_feedback_type() {
      axios.get('/feedback/product/types/').then(
          response => {
            let data = JSON.parse(response.data).data;
            this.feedback_types = []
            data.forEach(item => {
              this.feedback_types.push(
                  {
                    value: item,
                    label: item
                  }
              )
            })
          },
          // 失败
          error => {
            this.$message.error({message: error.response.data.message, showClose: true});
            this.feedback_types = [];
          })
    },
    query_departments() {
      axios.get('/feedback/departments/').then(
          response => {
            let data = JSON.parse(response.data).data;
            this.departments = []
            data.forEach(item => {
              this.departments.push(
                  {
                    value: item,
                    label: item
                  }
              );
              if (this.select_departments.length < 10) {
                this.select_departments.push(item);
              }
            })
          },
          // 失败
          error => {
            this.$message.error({message: error.response.data.message, showClose: true});
            this.departments = [];
          })
    },
    query_hospitals() {
      axios.get('/feedback/hospitals/', {
            params: {
              product_models: this.select_models,
              date_range: this.date_range
            }
      }).then(
          response => {
            let data = JSON.parse(response.data).data;
            this.hospitals = []
            this.select_hospitals = []
            data.forEach(item => {
              this.hospitals.push(
                  {
                    value: item,
                    label: item
                  }
              );
              if (this.select_hospitals.length < 10) {
                this.select_hospitals.push(item);
              }
            })
          },
          // 失败
          error => {
            this.$message.error({message: error.response.data.message, showClose: true});
            this.hospitals = [];
          })
    },
    query_product_models() {
      axios.get('/feedback/product/models/').then(
          response => {
            let data = JSON.parse(response.data).data;
            this.product_models = []
            this.sub_product_models = []
            data.forEach(item => {
              this.product_models.push(
                  {
                    value: item,
                    label: item
                  }
              )
              this.sub_product_models.push(
                  {
                    value: item,
                    label: item
                  }
              )
            })
          },
          // 失败
          error => {
            this.$message.error({message: error.response.data.message, showClose: true});
            this.product_models = [];
            this.sub_product_models = [];
          })
    },
    initPlot() {
      axios.post('/feedback/figure/6/', {
            params: {
              date_list: this.date_range,
              product_models: this.select_models,
              sub_product_models: this.select_sub_models,
              feedback_type: this.select_feedback_type,
              hospitals: this.select_hospitals,
              departments: this.select_departments
            }
          }
      ).then(
          response => {
            let res = JSON.parse(response.data)
            this.option.xAxis[0].data = res.xAxis;
            this.option.yAxis[0].max = Math.max(...res.total);
            this.option.yAxis[0].interval = Math.ceil(Math.max(...res.total) / 10);
            this.option.series = [];
            Object.keys(res.series).forEach(key => {
              this.option.series.push(
                  {
                    name: key,
                    type: 'bar',
                    stack: 'Ad',
                    label: {
                      normal: {
                        show: true,
                        position: 'inside', // 显示位置
                        formatter: function (params) {
                          if (params.value === 0) {  //为0时不显示
                            return ''
                          } else {
                            return params.value
                          }
                        }
                      }
                    },
                    tooltip: {
                      valueFormatter: function (value) {
                        return value;
                      }
                    },
                    emphasis: {
                      focus: 'series'
                    },
                    data: res.series[key]
                  }
              )
            });
            this.option.series.push(
                {
                    name: '总计',
                    type: 'bar',
                    label: {
                      normal: {
                        show: true,
                        position: 'top', // 显示位置
                        formatter: function (params) {
                            return params.value
                        }
                      }
                    },
                  z: -3,
                  barGap: '-100%',
                  tooltip: {
                      valueFormatter: function (value) {
                        return value;
                      }
                    },
                    emphasis: {
                      focus: 'series'
                    },
                    data: res.total
                  }
            );
            this.option.legend.data = Object.keys(res.series);
            this.chart.setOption(this.option);
            this.chart.resize();
            this.selectChange()
          },
          // 失败
          error => {
            this.$message.error({message: error.response.data.message, showClose: true});
          })
    },
    selectChange() {
      this.query_hospitals();
      axios.post('/feedback/figure/6/', {
            params: {
              date_list: this.date_range,
              product_models: this.select_models,
              sub_product_models: this.select_sub_models,
              feedback_type: this.select_feedback_type,
              hospitals: this.hospitals.map(obj => obj.value),
              departments: this.select_departments
            }
          }
      ).then(
          response => {
            let res = JSON.parse(response.data)
            this.data = res;
            this.option.xAxis[0].data = res.xAxis;
            this.option.yAxis[0].max = Math.max(...res.total);
            this.option.yAxis[0].interval = Math.ceil(Math.max(...res.total) / 10);
            this.option.series = [];
            Object.keys(res.series).forEach(key => {
              this.option.series.push(
                  {
                    name: key,
                    type: 'bar',
                    stack: 'Ad',
                    label: {
                      normal: {
                        show: true,
                        position: 'inside', // 显示位置
                        formatter: function (params) {
                          if (params.value === 0) {  //为0时不显示
                            return ''
                          } else {
                            return params.value
                          }
                        }
                      }
                    },
                    tooltip: {
                      valueFormatter: function (value) {
                        return value;
                      }
                    },
                    emphasis: {
                      focus: 'series'
                    },
                    data: res.series[key]
                  }
              )
            });
            this.option.series.push(
                {
                    name: '总计',
                    type: 'bar',
                    label: {
                      normal: {
                        show: true,
                        position: 'top', // 显示位置
                        formatter: function (params) {
                          return params.value
                        }
                      }
                    },
                    z: -3,
                    barGap: '-100%',
                    tooltip: {
                    valueFormatter: function (value) {
                      return value;
                    }
                  },
                    emphasis: {
                      focus: 'series'
                    },
                    data: res.total
                  }
            );
            this.option.legend.data = Object.keys(res.series);
            this.chart.setOption(this.option);
            this.chart.resize();
            this.hospitals = res.xAxis.map(obj => ({key:obj, value:obj}))
            this.select_hospitals = res.xAxis.slice(0, 10)
            this.selectSubChange()
          },
          // 失败
          error => {
            this.$message.error({message: error.response.data.message, showClose: true});
          })
    },
    selectSubChange() {
      let res = JSON.parse(JSON.stringify(this.data)); // 深拷贝对象
      if (this.select_hospitals.length === 0) {
        this.select_hospitals = res.xAxis.slice(10)
      }
      let indexOfData = res.xAxis.filter(item => this.select_hospitals.includes(item));
      indexOfData = indexOfData.map(obj => res.xAxis.indexOf(obj));
      res.xAxis = indexOfData.map(index => res.xAxis[index])
      this.option.xAxis[0].data = res.xAxis;
      this.option.yAxis[0].max = Math.max(...res.total);
      this.option.yAxis[0].interval = Math.ceil(Math.max(...res.total) / 10);
      this.option.series = [];
      Object.keys(res.series).forEach(key => {
        this.option.series.push(
            {
              name: key,
              type: 'bar',
              stack: 'Ad',
              label: {
                normal: {
                  show: true,
                  position: 'inside', // 显示位置
                  formatter: function (params) {
                    if (params.value === 0) {  //为0时不显示
                      return ''
                    } else {
                      return params.value
                    }
                  }
                }
              },
              tooltip: {
                valueFormatter: function (value) {
                  return value;
                }
              },
              emphasis: {
                focus: 'series'
              },
              data: res.series[key]
            }
        )
      });
      this.option.series.push(
          {
            name: '总计',
            type: 'bar',
            label: {
              normal: {
                show: true,
                position: 'top', // 显示位置
                formatter: function (params) {
                  return params.value
                }
              }
            },
            z: -3,
            barGap: '-100%',
            tooltip: {
              valueFormatter: function (value) {
                return value;
              }
            },
            emphasis: {
              focus: 'series'
            },
            data: res.total
          }
      );
      this.option.legend.data = Object.keys(res.series);
      this.chart.setOption(this.option);
      this.chart.resize();

    },
    initFigure() {
      const chartDom = document.getElementById('feedback-figure-6');
      this.chart = echarts.init(chartDom);
      this.chart.setOption(this.option);
      this.chart.resize();
      this.chart.on('click', function (params) {
        this.exportChartData([params.name]);
      }.bind(this));
    },
    handleResize() {
      if (this.chart) {
        this.chart.resize();
      }
    }
  },
  mounted() {
    this.initFigure()
    window.addEventListener('resize', this.handleResize)
    this.$nextTick(() => {
      this.chart.resize()
    })
  }
}
</script>

<style scoped lang="scss">
.transfer-footer {
  margin-left: 20px;
  padding: 6px 5px;
}

.el-main {
  background-color: #E9EEF3;
  color: #333;
  text-align: center;
  //line-height: 160px;
}

.el-date-editor--monthrange.el-input__inner {
  width: 400px;
}

#feedback-figure-6 {
  position: relative;
  height: 750px;
}

.el-checkbox {
  text-align: right;
  width: 100%;
  padding-right: 10px;
}

.el-row {
  margin-bottom: 10px;
  &:last-child {
    margin-bottom: 0;
  }
}
.el-tag {
  margin-right: 10px;
}
</style>